package com.nc.cloud.authority.server.service.impl;


import com.nc.cloud.api.vo.user.UserInfo;
import com.nc.cloud.authority.common.util.jwt.JWTInfo;
import com.nc.cloud.authority.server.feign.IUserService;
import com.nc.cloud.authority.server.service.AuthService;
import com.nc.cloud.authority.server.util.user.JwtAuthenticationRequest;
import com.nc.cloud.authority.server.util.user.JwtTokenUtil;
import com.nc.cloud.common.exception.auth.UserInvalidException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @Author:NCCloud
 * @Description: TODO
 * @Param:
 * @Data:  2020/3/26 16:28
 * @return
 */

@Service
public class AuthServiceImpl implements AuthService {

    private JwtTokenUtil jwtTokenUtil;
    /**
     * 对应 Feign 下的接口
     */
    private IUserService userService;

    @Autowired
    public AuthServiceImpl(JwtTokenUtil jwtTokenUtil, IUserService userService) {
        this.jwtTokenUtil = jwtTokenUtil;
        this.userService = userService;
    }

    /**
     * 登陆调用方法
     * */
    @Override
    public String login(JwtAuthenticationRequest authenticationRequest) throws Exception {

        //1 用户验
        UserInfo info = userService.validate(authenticationRequest);

        if (!StringUtils.isEmpty(info.getUid())) {
            //2 生成Token
            return jwtTokenUtil.generateToken(new JWTInfo(info.getAccount(), info.getUid(), info.getName(),info.getCode()));
        }
        throw new UserInvalidException("用户不存在或账户密码错误!");
    }

    @Override
    public void validate(String token) throws Exception {
        jwtTokenUtil.getInfoFromToken(token);
    }

    @Override
    public String refresh(String oldToken) throws Exception {
        return jwtTokenUtil.generateToken(jwtTokenUtil.getInfoFromToken(oldToken));
    }
}
